﻿using System;
using System.Diagnostics;
using System.Xml;
using log4net;
using log4net.Core;
using log4net.Layout;

namespace System
{
  public static class Logger
  {
    public static readonly ILog log = LogManager.GetLogger(typeof(Logger));

    static Logger()
    {
      //Log 4 NET Configuration
      log4net.Config.XmlConfigurator.Configure();
    }
  }

  public class Log4netXmlLayout : XmlLayoutBase
  {
    protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
    {

      writer.WriteStartElement("LogEntry");

      writer.WriteStartElement("Level");
      writer.WriteString(loggingEvent.Level.DisplayName);
      writer.WriteEndElement();

      writer.WriteStartElement("Message");
      writer.WriteCData(loggingEvent.RenderedMessage);
      writer.WriteEndElement();

      writer.WriteStartElement("Details");
      if (loggingEvent.ExceptionObject != null)
        writer.WriteCData(loggingEvent.ExceptionObject.ToString());
      writer.WriteEndElement();

      writer.WriteStartElement("StackTrace");

      if (loggingEvent.ExceptionObject != null)
      {
        writer.WriteCData(string.IsNullOrEmpty(loggingEvent.ExceptionObject.StackTrace) ? string.Empty : loggingEvent.ExceptionObject.StackTrace);
        //Exception Details
        {
          // Get stack trace for the exception with source file information
          var st = new StackTrace(loggingEvent.ExceptionObject, true);
          // Get the top stack frame
          var frame = st.GetFrame(0);

          if (frame != null)
          {
            // Get the line number from the stack frame
            var line = frame.GetFileLineNumber();

            string error_dtls = string.Format("\nFile: {0} -> Line:{1}", frame.GetFileName(), frame.GetFileLineNumber());
            writer.WriteCData(error_dtls);
          }
        }

        writer.WriteEndElement();
      }


      writer.WriteStartElement("TimeStamp");
      writer.WriteString(loggingEvent.TimeStamp.ToString("dd/MM/yyyy HH:mm:ss"));
      writer.WriteEndElement();

      writer.WriteEndElement();
    }
  }

}
